package com.llb666.shop.user.domain.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.llb666.shop.user.api.vo.auth.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 基于JWT的token生成与验证.
 *
 * @author llb666
 */
@Slf4j
@Service
public class JwtService {

    /**
     * 生产环境需要加密获取
     */
    private static final String KEY = "shop";
    private static final String ISSUER = "shop-user-name";
    private static final long TOKEN_EXP_TIME = 24 * 3600 * 1000;


    /**
     * 生成token.
     *
     * @param account 权限账户
     * @return token
     */
    public String token(Account account) {
        Date dateNow = new Date();
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String token = JWT.create()
                .withIssuedAt(dateNow)
                .withIssuer(ISSUER)
                .withExpiresAt(new Date(dateNow.getTime() + TOKEN_EXP_TIME))
                .withClaim("userId", account.getUserId())
                .sign(algorithm);
        log.info("jwt userId:{}", account.getUserId());
        return token;
    }

    /**
     * 验证token.
     *
     * @param token    token
     * @param userId 用户名
     * @return true/false
     */
    public boolean verify(String token, String userId) {
        log.info("userId:{}", userId);
        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .withClaim("userId", userId)
                    .build();
            verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
